import { NextRequest, NextResponse } from 'next/server';
import { DocumentOperations } from '@/lib/database-operations';
import { documentProcessor, FileProcessor } from '@/lib/vectorization';
import { writeFile, mkdir } from 'fs/promises';
import { join } from 'path';
import { existsSync } from 'fs';

// 配置最大文件大小
const MAX_FILE_SIZE = parseInt(process.env.MAX_FILE_SIZE || '10485760'); // 10MB
const UPLOAD_DIR = process.env.UPLOAD_DIR || './uploads';

export async function POST(request: NextRequest) {
  try {
    // 解析表单数据
    const formData = await request.formData();
    const file = formData.get('file') as File;
    const title = formData.get('title') as string;
    const userId = (formData.get('userId') as string) || undefined;

    if (!file) {
      return NextResponse.json(
        { success: false, error: '未选择文件' },
        { status: 400 }
      );
    }

    // 验证文件类型
    if (!FileProcessor.isValidFileType(file)) {
      return NextResponse.json(
        { success: false, error: '不支持的文件类型' },
        { status: 400 }
      );
    }

    // 验证文件大小
    if (!FileProcessor.isValidFileSize(file, MAX_FILE_SIZE)) {
      return NextResponse.json(
        {
          success: false,
          error: `文件大小超过限制 (${MAX_FILE_SIZE / 1024 / 1024}MB)`,
        },
        { status: 400 }
      );
    }

    // 提取文件内容
    let content: string;
    try {
      content = await FileProcessor.extractTextFromFile(file);
    } catch (error) {
      return NextResponse.json(
        { success: false, error: '文件内容提取失败' },
        { status: 400 }
      );
    }

    if (!content.trim()) {
      return NextResponse.json(
        { success: false, error: '文件内容为空' },
        { status: 400 }
      );
    }

    // 创建上传目录
    if (!existsSync(UPLOAD_DIR)) {
      await mkdir(UPLOAD_DIR, { recursive: true });
    }

    // 生成文件名
    const timestamp = Date.now();
    const fileName = `${timestamp}-${file.name}`;
    const filePath = join(UPLOAD_DIR, fileName);

    // 保存文件
    const bytes = await file.arrayBuffer();
    const buffer = Buffer.from(bytes);
    await writeFile(filePath, buffer);

    // 创建文档记录
    const documentId = await DocumentOperations.create({
      title: title || file.name,
      content,
      file_path: filePath,
      file_type: file.type || 'unknown',
      file_size: file.size,
      user_id: userId,
      created_at: new Date().toISOString(),
      metadata: {
        original_name: file.name,
        upload_timestamp: timestamp,
        content_length: content.length,
      },
    });

    // 异步处理文档向量化
    documentProcessor
      .processDocument(documentId, content, {
        title: title || file.name,
        file_type: file.type,
        user_id: userId,
      })
      .catch(error => {
        console.error('文档向量化处理失败:', error);
      });

    return NextResponse.json({
      success: true,
      data: {
        document_id: documentId,
        title: title || file.name,
        file_size: file.size,
        content_length: content.length,
      },
      message: '文件上传成功，正在处理中...',
    });
  } catch (error) {
    console.error('文件上传失败:', error);
    return NextResponse.json(
      { success: false, error: '文件上传失败' },
      { status: 500 }
    );
  }
}

// 获取文档列表
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const userId = searchParams.get('userId') || undefined;
    const limit = parseInt(searchParams.get('limit') || '50');
    const offset = parseInt(searchParams.get('offset') || '0');

    const documents = await DocumentOperations.getAll(userId, limit, offset);

    return NextResponse.json({
      success: true,
      data: documents,
    });
  } catch (error) {
    console.error('获取文档列表失败:', error);
    return NextResponse.json(
      { success: false, error: '获取文档列表失败' },
      { status: 500 }
    );
  }
}
